/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			ETSI_Fract.cc
  \date			september 2011
  \author		TNick

  \brief		Contains the implementation for ETSI_Fract class


  Copyright (c) 2011, Nicu Tofan
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
 * Neither the name of the copyright holder nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL NICU TOFAN BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include	<QFontMetrics>
#include	<QPainter>

#include	<sheet/ETSheetView.h>
#include	<sheet/ETSheet.h>
#include	<sheet/subitems/ETSI_Root.h>
#include	<sheet/subitems/ETSI_SText.h>

#include	"ETSI_Fract.h"

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */
DDHC_CONTENT(ETSI_Fract)

/* ------------------------------------------------------------------------- */
ETSI_Fract::ETSI_Fract	( void )
	: ETSubItem()
{
	top_pos = 0;
	btm_pos = 0;

	ETSI_SText * only_it;
	only_it = new ETSI_SText();
	top_block.append(only_it);

	only_it = new ETSI_SText();
	btm_block.append(only_it);

	DDHC_CONSTRUCT;
	DDHC_SUBITEM_VARS;
	DDHC_VARIABLE(top_pos);
	DDHC_VARIABLE(btm_pos);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
ETSI_Fract::~ETSI_Fract	( void )
{
	DDHC_DESTRUCT
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
qreal				ETSI_Fract::alignSize		(void)
{
	QFontMetrics f_m(font());
	return f_m.height() / 10;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void				ETSI_Fract::hitTest		(HtData * h_data)
{

	/* get the bounding box for the TOP sub-item in it's own coordinate system */
	h_data->rct_cache = top_block.boundingBox();
	/* transform that coordinates in this item's coordinate system */
	h_data->rct_cache.translate(top_block.posX(), top_pos);
	/* now convert them to ETI_CplxTxt item coordinates */
	h_data->rct_cache.translate(h_data->ref_pt);

	if (h_data->rct_cache.contains(h_data->ck_pt))
		{
			/* we already have computed the bounding box for this item */
			h_data->rct_bbx = h_data->rct_cache;
			/* and we're a step away from the reference point in item coords */
			h_data->ref_pt.setX(h_data->ref_pt.x()+top_block.posX());
			h_data->ref_pt.setY(h_data->ref_pt.y()+top_pos);
			top_block.hitTest(h_data);
			return;
		}


	/* get the bounding box for the BOTTOM sub-item in it's own coordinate system */
	h_data->rct_cache = btm_block.boundingBox();
	/* transform that coordinates in this item's coordinate system */
	h_data->rct_cache.translate(btm_block.posX(), btm_pos);
	/* now convert them to ETI_CplxTxt item coordinates */
	h_data->rct_cache.translate(h_data->ref_pt);

	if (h_data->rct_cache.contains(h_data->ck_pt))
		{
			/* we already have computed the bounding box for this item */
			h_data->rct_bbx = h_data->rct_cache;
			/* and we're a step away from the reference point in item coords */
			h_data->ref_pt.setX(h_data->ref_pt.x()+btm_block.posX());
			h_data->ref_pt.setY(h_data->ref_pt.y()+btm_pos);
			btm_block.hitTest(h_data);
			return;
		}


	h_data->it_hitted = this;
	h_data->true_hit = true;
	/* h_data->rct_bbx already set by the caller */
	h_data->int_data = 0;

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void				ETSI_Fract::paint		(
		ETSheetView * vp, QPainter * painter, QPointF pt_ref )
{

	PaintData	pd(vp, painter, pt_ref);
	prePaint(&pd);

	qreal init_y = pt_ref.y();

	/* the dividing line */
	pt_ref.setX(pt_ref.x() - top_block.posX());
	painter->drawLine(pt_ref.x(), init_y, pt_ref.x() + bbox.width(), init_y);

	pt_ref.setX(pt_ref.x() + top_block.posX());

	pt_ref.setY(init_y + top_pos);
	top_block.paint(vp, painter, pt_ref);

	pt_ref.setY(init_y + btm_pos);
	btm_block.paint(vp, painter, pt_ref);

	postPaint(&pd);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void				ETSI_Fract::recompute	(bool b_full)
{


	if (b_full == false)
	{ /* only recompute if this element is "dirty" */

		/* the SIZE_DIRTY flag means that we should recompute the alignment
  value and all items that rely on this font. */
		if (isSizeDirty())
		{
			top_block.recompute(true);
			btm_block.recompute(true);
		}
		else if (isKidSizeDirty())
		{
			if (top_block.requireRecompute())
			{
				top_block.recompute(b_full);
			}
			if (btm_block.requireRecompute())
			{
				btm_block.recompute(b_full);
			}
		}
		else
		{
			return;
		}
	}
	else
	{ /* forced recompute */
		top_block.recompute(b_full);
		btm_block.recompute(b_full);
	}

	qreal sz_alg = alignSize();
	qreal h_top = top_block.boundingBox().height();
	qreal h_btm = btm_block.boundingBox().height();
	qreal w_top = top_block.boundingBox().width();
	qreal w_btm = btm_block.boundingBox().width();
	qreal b_w = (w_top > w_btm ? w_top : w_btm);

	top_block.setPosX(sz_alg);
	btm_block.setPosX(sz_alg);

	top_pos = (-1)*(h_top / 2 + sz_alg);
	btm_pos = h_btm / 2 + sz_alg;

	bbox = QRectF(0, -(h_top + sz_alg), b_w + 2*sz_alg, h_top + h_btm + 2*sz_alg);
	//	QRectF(qreal left, qreal top, qreal width, qreal height);

	/* reset the flags that request a recompute */
	resetSizeFlags();

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
ETSI_Fract *		ETSI_Fract::loadXML		(
		QDomElement dom_e)
{

	QDomElement		dom_it;
	QDomElement		dom_it2;
	QDomElement		dom_sit;
	ETSI_Fract *	ret_it;

#ifdef	APP_DEBUG
	/* type is assumed to be fraction */

	dom_it = dom_e.firstChildElement(XML_TAG_TYPE);
	if (!dom_it.isNull())
	{
		Q_ASSERT_X(dom_it.text() == XML_SIT_FRACT, __FUNCTION__,
				   QString("ETSI_Root::loadXML got an element of type <"
						   "%1> while expected type is " XML_SIT_FRACT)
				   .arg(dom_it.text()).toLatin1()
				   );
	}
#endif

	/* create this element */
	ret_it = new ETSI_Fract();


	/* the one and only common data to all kinds of sub-items */
	dom_it = dom_e.firstChildElement(XML_TAG_COMM);
	if (!dom_it.isNull())
	{
		ETSubItem::loadXMLCmn(ret_it, dom_it);

		if (!dom_it.nextSiblingElement(XML_TAG_COMM).isNull())
		{
			qDebug() << "The input presented more than one "
					 << "common tags, when only one per sub-item element "
					 << "is allowed";
		}
	}

	/* load particular data */

	dom_it = dom_e.firstChildElement(XML_TAG_DENOM);
	if (!dom_it.isNull())
	{

		/* the one and only sub-item that has to be of root type */
		dom_it2 = dom_e.firstChildElement(XML_TAG_SUBITEM);
		if (!dom_it.isNull())
		{
			dom_sit = dom_it2.firstChildElement(XML_TAG_TYPE);
			if (!dom_sit.isNull())
			{ /* silently ignore the lack of type and assume root */

				if (dom_sit.text() != XML_SIT_ROOT)
				{

					qDebug() << "The input presented an sub-item that "
							 << "was not of root type. The only "
							 << "sub-item in a denominator needs to be "
							 << "of root type. Period.";
					delete ret_it;
					return NULL;

				}
			}

			/* this call will load entire chain of sub-items */
			ETSI_Root::loadXML(dom_it2, &ret_it->top_block);


			if (!dom_it2.nextSiblingElement(XML_TAG_SUBITEM).isNull())
			{
				qDebug() << "The input presented to ETSI_Fract::loadXML more than one "
						 << XML_TAG_SUBITEM << " tags, when only one per sub-item element "
						 << "is allowed";
			}
		}

		if (!dom_it.nextSiblingElement(XML_TAG_DENOM).isNull())
		{
			qDebug() << "The input presented to ETSI_Fract::loadXML more than one "
					 << XML_TAG_DENOM << " tags, when only one per sub-item element "
					 << "is allowed";
		}
	}



	dom_it = dom_e.firstChildElement(XML_TAG_NUMERATOR);
	if (!dom_it.isNull())
	{

		/* the one and only sub-item that has to be of root type */
		dom_it2 = dom_e.firstChildElement(XML_TAG_SUBITEM);
		if (!dom_it.isNull())
		{
			dom_sit = dom_it2.firstChildElement(XML_TAG_TYPE);
			if (!dom_sit.isNull())
			{ /* silently ignore the lack of type and assume root */

				if (dom_sit.text() != XML_SIT_ROOT)
				{

					qDebug() << "The input presented an sub-item that "
							 << "was not of root type. The only "
							 << "sub-item in a numerator needs to be "
							 << "of root type. Period.";
					delete ret_it;
					return NULL;

				}
			}

			/* this call will load entire chain of sub-items */
			ETSI_Root::loadXML(dom_it2, &ret_it->top_block);


			if (!dom_it2.nextSiblingElement(XML_TAG_SUBITEM).isNull())
			{
				qDebug() << "The input presented to ETSI_Fract::loadXML more than one "
						 << XML_TAG_SUBITEM << " tags, when only one per sub-item element "
						 << "is allowed";
			}
		}

		if (!dom_it.nextSiblingElement(XML_TAG_NUMERATOR).isNull())
		{
			qDebug() << "The input presented to ETSI_Fract::loadXML more than one "
					 << XML_TAG_NUMERATOR << " tags, when only one per sub-item element "
					 << "is allowed";
		}
	}



	return ret_it;


	return ret_it;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void				ETSI_Fract::saveXML		(
		QDomElement dom_e)
{
	QDomElement dom_it2;

	/* save the type */
	QDomElement dom_it = dom_e.ownerDocument().createElement(XML_TAG_TYPE);
	dom_e.appendChild(dom_it);
	QDomText dom_tx = dom_e.ownerDocument().createTextNode(XML_SIT_FRACT);
	dom_it.appendChild(dom_tx);


	/* save common properties */
	dom_it = dom_e.ownerDocument().createElement(XML_TAG_COMM);
	dom_e.appendChild(dom_it);
	saveXMLCmn(dom_it);


	/* now specifics */
	dom_it = dom_e.ownerDocument().createElement(XML_TAG_DENOM);
	dom_e.appendChild(dom_it);
	dom_it2 = dom_e.ownerDocument().createElement(XML_TAG_SUBITEM);
	dom_it.appendChild(dom_it2);
	top_block.saveXML(dom_it2);

	dom_it = dom_e.ownerDocument().createElement(XML_TAG_NUMERATOR);
	dom_e.appendChild(dom_it);
	dom_it2 = dom_e.ownerDocument().createElement(XML_TAG_SUBITEM);
	dom_it.appendChild(dom_it2);
	btm_block.saveXML(dom_it2);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool		ETSI_Fract::kidNavReq_up		(ETSheetView * vp, ETSubItem * kid)
{
	if (kid == &top_block)
	{
		if (fatherSubI() != NULL)
		{
			fatherSubI()->kidNavReq_up(vp, this);
			return true;
		}
	}
	else if (kid == &btm_block)
	{
		vp->setCurrentSubI(NULL, &top_block);
		return true;
	}

	return false;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool		ETSI_Fract::kidNavReq_down		(ETSheetView * vp, ETSubItem * kid)
{
	if (kid == &top_block)
	{
		vp->setCurrentSubI(NULL, &btm_block);
		return true;
	}
	else if (kid == &btm_block)
	{
		if (fatherSubI() != NULL)
		{
			fatherSubI()->kidNavReq_down(vp, this);
			return true;
		}
	}

	return false;
}
/* ========================================================================= */

/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
